import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';

class NumberLayoutController {
  bool decimal;
  num number = 0;
  NumberLayoutController(this.number, {this.decimal = false});

  NumberLayoutState? _state;
  void _attatch(NumberLayoutState state) {
    _state = state;
  }

  void _dettach() {
    _state = null;
  }

  void refresh() {
    _state?.refresh();
  }
}

class NumberLayout extends StatefulWidget {
  num initNumber;
  int max;
  int min;
  final editParentText;
  int newVal;
  NumberLayoutController controller;
  NumberLayout(
      {Key? key,
      this.initNumber = 0,
      this.min = 0,
      this.max = 1000,
      this.editParentText,
      this.newVal = 0,
      required this.controller})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return NumberLayoutState();
  }
}

class NumberLayoutState extends State<NumberLayout> {
  final _textController = TextEditingController(text: "");

  @override
  void initState() {
    super.initState();
    _textController.text = "${widget.initNumber}";
    widget.controller.number = widget.initNumber;
    widget.controller._attatch(this);
  }

  @override
  void dispose() {
    super.dispose();
    widget.controller._dettach();
  }

  void refresh() {
    setState(() {
      _textController.text = widget.controller.number.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 36.rpx,
      decoration: BoxDecoration(
        color: UIColor.color_input,
        borderRadius: BorderRadius.circular(8.rpx),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          UText.getBkButton("-", 18.rpx,
              color: UIColor.color_t1,
              bkColor: Colors.white,
              width: 24.rpx,
              height: 24.rpx,
              radius: 4.rpx, onPressed: () {
            // debugPrint((widget.controller.number * 10000 - 1 * 10000) / 10000);
            FocusManager.instance.primaryFocus?.unfocus();
            var temp = widget.controller.number - 1 >= 0
                ? widget.controller.number
                : -1;
            if (temp >= 0) {
              var count = NumUtil.subtractDec(widget.controller.number, 1);
              widget.controller.number = num.parse(count.toString());
              setState(() {
                _textController.text = widget.controller.number.toString();
                _textController.selection = TextSelection.fromPosition(
                    TextPosition(offset: _textController.text.length));
                widget.editParentText(); // 调用父级组件方法
              });
            }
          }),
          Container(
            width: 64.rpx,
            alignment: Alignment.centerRight,
            child: TextField(
                controller: _textController,
                style: UITextStyle.main_text,
                keyboardType: TextInputType.numberWithOptions(
                    decimal: widget.controller.decimal),
                maxLength: widget.controller.decimal
                    ? "${widget.max}".length + 2
                    : "${widget.max}".length,
                textAlign: TextAlign.center,
                decoration: const InputDecoration(
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.transparent,
                    ),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.transparent,
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.transparent,
                    ),
                  ),
                  counterText: "",
                  contentPadding: EdgeInsets.zero,
                ),
                //inputFormatters: [MaxNumberInputFormatter(min: widget.min, max: widget.max)],
                inputFormatters: [
                  XNumberTextInputFormatter(
                      maxIntegerLength: 5,
                      maxDecimalLength: widget.controller.decimal ? 2 : 0,
                      isAllowDecimal: widget.controller.decimal)
                ],
                onChanged: (text) {
                  //FocusManager.instance.primaryFocus?.unfocus();
                  try {
                    // abs绝对值
                    widget.controller.number = num.parse(text).abs();
                    widget.editParentText(); // 调用父级组件方法
                  } catch (e, st) {
                    Log.i("", e, st);
                    widget.controller.number = 0;
                  }
                },
                onEditingComplete: () {
                  FocusManager.instance.primaryFocus?.unfocus();
                }),
          ),
          UText.getBkButton("+", 18.rpx,
              color: Colors.white,
              bkColor: UIColor.color_primary,
              width: 24.rpx,
              height: 24.rpx,
              radius: 4.rpx, onPressed: () {
            FocusManager.instance.primaryFocus?.unfocus();
            if (widget.controller.number < widget.max) {
              setState(() {
                var count = NumUtil.addDec(widget.controller.number, 1);
                widget.controller.number = num.parse(count.toString());
                _textController.text = widget.controller.number.toString();
                _textController.selection = TextSelection.fromPosition(
                    TextPosition(offset: _textController.text.length));
                widget.editParentText(); // 调用父级组件方法
              });
            }
          }),
        ],
      ),
    );
  }
}

class MaxNumberInputFormatter extends TextInputFormatter {
  int max;
  int min;

  MaxNumberInputFormatter({this.max = 1, this.min = 0});

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    var curNum = 0.0;
    try {
      curNum = double.parse(newValue.text);
      // ignore: empty_catches
    } catch (e) {}
    if (curNum > max) {
      curNum = max * 1.0;
    }
    if (curNum < min) {
      curNum = min * 1.0;
    }
    var text = "$curNum";
    return TextEditingValue(
        text: text,
        selection:
            TextSelection.fromPosition(TextPosition(offset: text.length)));
  }
}

class XNumberTextInputFormatter extends TextInputFormatter {
  final int _maxIntegerLength;
  final int _maxDecimalLength;
  final bool _isAllowDecimal;

  /// [maxIntegerLength]限定整数的最大位数，为null时不限
  /// [maxDecimalLength]限定小数点的最大位数，为null时不限
  /// [isAllowDecimal]是否可以为小数，默认是可以为小数，也就是可以输入小数点
  XNumberTextInputFormatter(
      {int maxIntegerLength = 1,
      int maxDecimalLength = 0,
      bool isAllowDecimal = true})
      : _maxIntegerLength = maxIntegerLength,
        _maxDecimalLength = maxDecimalLength,
        _isAllowDecimal = isAllowDecimal;

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    String value = newValue.text.trim(); //去掉前后空格
    int selectionIndex = newValue.selection.end;
    if (_isAllowDecimal) {
      if (value == '.') {
        value = '0.';
        selectionIndex++;
      } else if (value != '' && _isToDoubleError(value)) {
        //不是double输入数据
        return _oldTextEditingValue(oldValue);
      }
      //包含小数点
      if (value.contains('.')) {
        int pointIndex = value.indexOf('.');
        String beforePoint = value.substring(0, pointIndex);
//      print('$beforePoint');
        String afterPoint = value.substring(pointIndex + 1, value.length);
//      print('$afterPoint');
        //小数点前面没内容补0
        if (beforePoint.isEmpty) {
          value = '0.${afterPoint}';
          selectionIndex++;
        } else {
          //限定整数位数
          if (null != _maxIntegerLength) {
            if (beforePoint.length > _maxIntegerLength) {
              return _oldTextEditingValue(oldValue);
            }
          }
        }
        //限定小数点位数
        if (null != _maxDecimalLength) {
          if (afterPoint.length > _maxDecimalLength) {
            return _oldTextEditingValue(oldValue);
          }
        }
      } else {
        //限定整数位数
        if (null != _maxIntegerLength) {
          if (value.length > _maxIntegerLength) {
            return _oldTextEditingValue(oldValue);
          }
        }
      }
    } else {
      if (value.contains('.') ||
          (value != '' && _isToDoubleError(value)) ||
          (null != _maxIntegerLength && value.length > _maxIntegerLength)) {
        return _oldTextEditingValue(oldValue);
      }
    }

    return TextEditingValue(
      text: value,
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }

  ///返回旧的输入内容
  TextEditingValue _oldTextEditingValue(TextEditingValue oldValue) {
    return TextEditingValue(
      text: oldValue.text,
      selection: TextSelection.collapsed(offset: oldValue.selection.end),
    );
  }

  ///输入内容不能解析成double
  bool _isToDoubleError(String value) {
    try {
      double.parse(value);
    } catch (e) {
      return true;
    }
    return false;
  }
}
